package com.xunk.common.redis.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
@Slf4j
public class RedisService {
    @Autowired
    public RedisTemplate redisTemplate;

    private static final Long SUCCESS = 1L;
    private long timeout = 9999; //获取锁的超时时间

    private Long time = 100L;// 以后删除

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        long start = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value);
        if (System.currentTimeMillis() - start > time)
            log.info(" Set操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, key);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        long start = System.currentTimeMillis();
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        T t = operation.get(key);
        if (System.currentTimeMillis() - start > time)
            log.info(" Get操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, key);
        return t;
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        long start = System.currentTimeMillis();
        List<T> range = redisTemplate.opsForList().range(key, 0, -1);
        if (System.currentTimeMillis() - start > time)
            log.info(" List get操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, key);
        return range;
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> long setCacheSet(final String key, final Set<T> dataSet) {
        Long count = redisTemplate.opsForSet().add(key, dataSet);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            long start = System.currentTimeMillis();
            redisTemplate.opsForHash().putAll(key, dataMap);
            if (System.currentTimeMillis() - start > time)
                log.info(" Map set操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, key);

        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        long start = System.currentTimeMillis();
        Map<String, T> entries = redisTemplate.opsForHash().entries(key);
        if (System.currentTimeMillis() - start > time)
            log.info(" Map get操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, key);

        return entries;
    }


    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 删除hashmap中的某个字段
     *
     * @param key  redis键
     * @param hKey hashmap键
     */
    public void delCacheMapValue(final String key, final String... hKey) {
        redisTemplate.opsForHash().delete(key, hKey);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
//        return redisTemplate.keys(pattern);
        long start = System.currentTimeMillis();
        List<String> scan = this.scan(pattern);
        if (System.currentTimeMillis() - start > time)
            log.info(" keys scan 操作Redis耗时：{},CacheKey:{}", System.currentTimeMillis() - start, pattern);

        return scan;
    }


    /**
     * 获取redis分布式锁，等待时间9999毫秒
     *
     * @param key        锁名称
     * @param value      锁值
     * @param expireTime 持有时间分钟
     * @param wait       是否等待
     * @return
     */
    public Boolean tryLock(String key, String value, long expireTime, boolean wait) {
        return this.tryLock(key, value, expireTime, TimeUnit.SECONDS, timeout, wait);
    }

    /**
     * 获取redis分布式锁
     *
     * @param key            锁名称
     * @param value          锁值
     * @param expireTime     持有时间
     * @param expireTimeUint 持有时间单位
     * @param waitTime       等待时间毫秒
     * @param wait           是否等待
     * @return
     */
    public Boolean tryLock(String key, String value, long expireTime, TimeUnit expireTimeUint, long waitTime, boolean wait) {

        Long start = System.currentTimeMillis();
        try {
            for (; ; ) {
                log.info("{}尝试抢{}锁", value, key);
                //SET命令返回OK ，则证明获取锁成功
                Boolean ret = Optional.ofNullable(redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, expireTimeUint)).orElse(false);
                if (ret) {
                    log.info("{}尝试抢{}锁成功", value, key);
                    return true;
                }
                //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
                long end = System.currentTimeMillis() - start;
                //是否等待
                if (!wait || end >= waitTime) {
                    log.info("{}等待抢{}锁失败", value, key);
                    return false;
                }
            }
        } finally {

        }
    }


    /**
     * redis分布式锁，释放锁，不支持重入
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean unlock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);

        Long result = (Long) redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        if (ObjectUtils.nullSafeEquals(result, SUCCESS)) {
            return true;
        }

        return false;
    }

    public List<String> scan(String pattern) {
        List<String> result = new ArrayList<>();

        ScanOptions options = ScanOptions.scanOptions().count(5000).match(pattern).build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        Cursor<String> cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
        Optional.ofNullable(cursor).ifPresent(s -> {
            while (s.hasNext()) {
                result.add(s.next());
            }
            try {
                s.close();
            } catch (Exception e) {
                System.out.println("关闭Cursor异常：" + e);
            }
        });
        return result;
    }

//    public Set<String> scan1(String pattern) {
//        return (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
//            Set<String> keysTmp = new HashSet<>();
//            Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(pattern).count(1000).build());
//            while (cursor.hasNext()) {
//                keysTmp.add(new String(cursor.next()));
//            }
//            return keysTmp;
//        });
//    }

    public Boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

}
